package com.dhecp.project.api.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.*;
import java.net.*;
import java.util.*;

/**
 * @ClassName ApiHttpUtils
 * @Description TODO
 * @Author alula
 * @Date 2022-08-26 15:08
 */
public class ApiHttpUtils {
    private static final Logger logger = LoggerFactory.getLogger(ApiHttpUtils.class);

    public static JSONObject sendGet(String url) {
        JSONObject jsonObject = null;
        jsonObject = httpRequest(url, "GET", null);
        return jsonObject;
    }

    public static JSONObject sendPost(String url) {
        JSONObject jsonObject = null;
        jsonObject = httpRequest(url, "POST", null);
        return jsonObject;
    }

    public static JSONObject sendPost(String url, String output) {
        JSONObject jsonObject = null;
        jsonObject = httpRequest(url, "POST", output);
        return jsonObject;
    }

    private static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
        JSONObject jsonObject = null;
        StringBuffer buffer = new StringBuffer();
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader bufferedReader = null;
        try {
            logger.debug("【ECPAPIHTTP】", "http请求request:{},method:{},output{}", new Object[]{requestUrl, requestMethod, outputStr});
            // 创建SSLContext对象，并使用我们指定的信任管理器初始化
            TrustManager[] tm = { new IX509TrustManager() };
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();
            URL url = new URL(requestUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setConnectTimeout(30000);
            connection.setReadTimeout(30000);
            connection.setUseCaches(false);
            connection.setRequestMethod(requestMethod);
            if (outputStr != null) {
                OutputStream out = connection.getOutputStream();
                out.write(outputStr.getBytes("UTF-8"));
                out.close();
            }
            inputStream = connection.getInputStream();
            inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
            bufferedReader = new BufferedReader(inputStreamReader);
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                buffer.append(line);
            }
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            inputStream = null;
            connection.disconnect();
            jsonObject = JSONObject.parseObject(buffer.toString());
        } catch (Exception ex) {
            Map<String,Object> errorMap = new HashMap<>();
            errorMap.put("success", false);
            errorMap.put("message", ex.getMessage());
            jsonObject = JSON.parseObject(JSON.toJSONString(errorMap));
            logger.error("【ECPAPIHTTP】", "http请求error:{}", new Object[]{ex.getMessage()});
        } finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
                if (inputStreamReader != null) {
                    inputStreamReader.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }

            } catch (ConnectException ce) {
                logger.error("【ECPAPIHTTP】", "http请求ConnectException:{}", new Object[]{ce.getMessage()});
            }catch (Exception ex) {
                ex.printStackTrace();
                logger.error("【ECPAPIHTTP】", "http请求Exception:{}", new Object[]{ex.getMessage()});
            }
        }
        return  jsonObject;
    }

    /**
     * sslPOST请求参数
     * @param data
     * @return
     */
    private static NameValuePair[] requestParams(Map<String, String> data) {
        NameValuePair[] nameValueList = new NameValuePair[data.size()];
        Iterator<Map.Entry<String, String>> it = data.entrySet().iterator();
        int i= 0;
        while (it.hasNext()) {
            Map.Entry<String, String> entry = (Map.Entry<String, String>) it.next();
            nameValueList[i] = new NameValuePair(entry.getKey(), entry.getValue());
            i++;
        }
        return nameValueList;
    }

    /**
     * 请求POST数据方法
     * @param url
     * @param params
     * @return
     */
    public static JSONObject sendHttpClientPost(String url,  Map<String, String> params){
        String result = "";
        JSONObject jsonObject = null;
        try {
            HttpClient httpClient = new HttpClient();
            httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(30 * 1000);
            httpClient.getHttpConnectionManager().getParams().setSoTimeout(30 * 1000);
            PostMethod postMethod = new PostMethod(url);
            if (params != null) {
                postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
                postMethod.setRequestBody(requestParams(params));
            }
            postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            httpClient.executeMethod(postMethod);
            result = new String(postMethod.getResponseBody(), "utf-8");
            if (postMethod != null) {
                postMethod.releaseConnection();
            }
            jsonObject = JSONObject.parseObject(result);
        } catch (ConnectException e)
        {
            logger.error("调用API接口sendPost失败 ConnectException, url=" + url + ",postData=" + JSON.toJSONString(params), e);
        }
        catch (SocketTimeoutException e)
        {
            logger.error("调用API接口sendPost失败 SocketTimeoutException, url=" + url + ",postData=" + JSON.toJSONString(params), e);
        }
        catch (IOException e)
        {
            logger.error("调用API接口sendPost失败 IOException, url=" + url + ",postData=" + JSON.toJSONString(params), e);
        }
        catch (Exception ex)
        {
            Map<String,Object> errorMap = new HashMap<>();
            errorMap.put("success", false);
            errorMap.put("message", ex.getMessage());
            jsonObject = JSONObject.parseObject(JSON.toJSONString(errorMap));
            logger.error("调用API接口sendPost失败 Exception, url=" + url + ",postData=" + JSON.toJSONString(params), ex);
        }
        return jsonObject;
    }


    /**
     * 格式化成URL请求参数，为&a=1&b=1格式
     * @param params
     * @return
     * @throws IOException
     */
    public static String buildQuery(Map<String, Object> params)
            throws IOException
    {
        if ((params == null) || (params.isEmpty())) {
            return "";
        }
        StringBuilder query = new StringBuilder();
        Set<Map.Entry<String, Object>> entries = params.entrySet();
        boolean hasParam = false;
        for (Map.Entry<String, Object> entry : entries)
        {
            String name = (String)entry.getKey();
            Object value = entry.getValue();
            if (value != null)
            {
                if (hasParam) {
                    query.append("&");
                } else {
                    hasParam = true;
                }
                query.append(name).append("=").append(URLEncoder.encode(String.valueOf(value), "utf-8"));
            }
        }
        return query.toString();
    }

    /**
     * 获取完整的url
     * @param url 请求uri
     * @param params 请求参数
     * @return
     */
    public static String getWholeUrl(String url, Map<String, String> params){
        if(url == null){
            return null;
        }
        if(params == null){
            return url;
        }
        Set<Map.Entry<String, String>> set = params.entrySet();
        if(set.size() <= 0){
            return url;
        }
        url += "?";
        Iterator<Map.Entry<String, String>> it = set.iterator();
        if(it.hasNext()){
            Map.Entry<String, String> entry = (Map.Entry<String, String>) it.next();
            String param = entry.getKey() + "=" + entry.getValue();
            url += param;
        }
        while(it.hasNext()){
            Map.Entry<String, String> entry = (Map.Entry<String, String>) it.next();
            String param = entry.getKey() + "=" + entry.getValue();
            url += "&" + param;
        }
        return url;
    }
}
